package com.example.guet_assistant.service.impl;

import com.example.guet_assistant.domain.vo.MessageVO;
import com.example.guet_assistant.handler.MyWebSocketHandler;
import com.example.guet_assistant.pojo.entity.Message;
import com.example.guet_assistant.service.MessageService;
import com.example.guet_assistant.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MessageScheduler {
    @Autowired
    MessageService messageService;

    @Autowired
    private MyWebSocketHandler webSocketHandler;  // WebSocket 处理器

    @Scheduled(fixedRate = 10000)  // 每 10 秒检查一次
    public void checkAndPublishMessage() throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDate = new Date();
        String formattedDate = formatter.format(currentDate);
        // 查询需要发布的消息
        List<Message> messagesToPublish = messageService.findMessagesToPublish(formattedDate);

        // 遍历消息列表并通过 WebSocket 发送
        for (Message message : messagesToPublish) {
            messageService.regularMessage(message);  // 如果需要，处理消息
            webSocketHandler.sendObjectToAll(message);  // 将消息通过 WebSocket 发送
            System.out.println("消息已通过 WebSocket 发送：" + message);
        }
    }
}
